<template>
  <div>
    <el-breadcrumb class="breadcrumb-row" separator-class="el-icon-arrow-right">
      <el-breadcrumb-item>图书管理</el-breadcrumb-item>
      <el-breadcrumb-item>图书信息添加</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-steps :active="Number(activeTab)" simple>
        <el-step title="信息完善" icon="el-icon-s-order"></el-step>
        <el-step title="作者完善" icon="el-icon-s-custom"></el-step>
        <el-step title="出版完善" icon="el-icon-upload"></el-step>
        <el-step title="描述完善" icon="el-icon-picture"></el-step>
      </el-steps>
      <el-row :gutter="20" class="content-row">
        <el-col :span="16">
          <el-form :model="addForm" :rules="addrules" ref="addbookForm">
            <el-tabs tab-position="left" v-model="activeTab" :before-leave="beforeLeave">
              <el-tab-pane label="书籍信息" name="1">

                <el-form-item label="书籍名称" prop="bookName">
                  <el-input v-model="addForm.bookName"></el-input>
                </el-form-item>
                <el-form-item label="书籍价格" prop="price">
                  <el-input v-model="addForm.price"></el-input>
                </el-form-item>
                <el-form-item label="书籍数量" prop="count">
                  <el-input v-model="addForm.count"></el-input>
                </el-form-item>
              </el-tab-pane>
              <el-tab-pane label="书籍作者" name="2">
                <el-form-item label="作者名称" prop="author">
                  <el-input v-model="addForm.author"></el-input>
                </el-form-item>
              </el-tab-pane>
              <el-tab-pane label="书籍出版" name="3">
                <el-form-item label="出版社" prop="publish">
                  <el-input v-model="addForm.publish"></el-input>
                </el-form-item>
                <el-form-item label="出版时间" prop="createTime">
                  <el-date-picker format="yyyy 年 MM 月 dd 日" value-format="yyyy-MM-dd" v-model="addForm.createTime"
                    type="date" placeholder="选择日期">
                  </el-date-picker>
                </el-form-item>
              </el-tab-pane>
              <el-tab-pane label="书籍描述" name="4">
                <el-form-item label="书籍的简要描述" prop="descriptions">
                  <el-input type="textarea" placeholder="请输入书籍的简要描述...." v-model="addForm.descriptions" maxlength="1000"
                    show-word-limit rows="12"></el-input>
                </el-form-item>
                <el-button v-if="edit" type="primary" @click="upBookClick">编辑图书</el-button>
                <el-button v-else type="primary" @click="addBookClick">添加图书</el-button>
              </el-tab-pane>
            </el-tabs>
          </el-form>
        </el-col>
        <el-col :span="8">
          <!-- <img v-if="image" src="../../assets/imgs/book.jpg" /> -->
          <el-upload class="avatar-uploader" action="user/common/upload" :show-file-list="false"
            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" :headers="{ 'token': token }">
            <img v-if="addForm.image" :src="imgBaseUrl + addForm.image" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div>点击更换图片</div>
          </el-upload>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script>
import * as dayjs from 'dayjs'

import { addBook, selectBookById, updateBook } from '@/request'

import { imgBase } from '@/config/base'

export default {
  data () {
    return {
      imgBaseUrl: imgBase,
      token: JSON.parse(sessionStorage.getItem('token')),
      edit: false,
      addForm: {
        bookName: '',
        author: '',
        publish: '',
        createTime: '',
        price: '',
        image: '',
        count: 0,
        // ISBN: "",
        descriptions: ''
      },
      addrules: {
        bookName: [
          { required: true, message: '书籍名称不能为空', trigger: 'blur' }
        ],
        author: [
          { required: true, message: '作者名称不能为空', trigger: 'blur' }
        ],
        publish: [{ required: true, message: '出版社不能为空', trigger: 'blur' }],
        createTime: [
          { required: true, message: '出版时间不能为空', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '书籍价格不能为空', trigger: 'blur' },
          {
            type: 'number',
            message: '必须为数字',
            trigger: 'blur',
            transform: (value) => Number(value)
          }
        ],
        // ISBN: [{ required: true, message: "ISBN不能为空", trigger: "blur" }],
        descriptions: [
          { required: true, message: '书记描述不能为空', trigger: 'blur' }
        ]
      },
      activeTab: '1'
    }
  },
  watch: {
    $route: {
      immediate: true,
      handler () {
        if (this.$route.params && this.$route.params.id) {
          // 需要监听的参数
          this.edit = true
          this.editBookInfo(this.$route.params.id)
        }
      }
    }
  },
  methods: {
    handleAvatarSuccess (res) {
      this.addForm.image = res.data
      // console.log(res.data);
    },
    beforeAvatarUpload (file) {
      // const isJPG = file.type === 'image/jpeg'
      // console.log(file);
    },
    async getBook (id) {
      const data = await selectBookById({ bookId: id })
      // if (data.code != 200) {
      //   this.$message.error("该图书不存在，请重新输入正确的图书ID！");
      //   return;
      // }
      // console.log(data.data);
      // console.log(dayjs(data.data.createTime).format("YYYY-MM-DD"));

      this.addForm = data.data
      this.addForm.createTime = dayjs(data.data.createTime).format('YYYY-MM-DD')
    },
    editBookInfo (id) {
      this.getBook(id)
    },
    beforeLeave (activeName, oldActiveName) {
      if (oldActiveName == 1) {
        if (!this.addForm.bookName || !this.addForm.price) {
          this.$message.error('请完善书籍的信息')
          return false
        }
        return true
      }
      return true
    },
    addBookClick () {
      this.$refs.addbookForm.validate(async (valid) => {
        if (!valid) return this.$message.error('请完善书籍表单的内容')
        // count,status加个选项卡
        const data = await addBook({
          ...this.addForm,
          updateTime: dayjs(Date.now()).unix(),
          count: 1,
          status: 1
          // id:10000
        })
        if (data.code != 200) return this.$message.error(data.msg)

        this.$message.success(data.msg)

        this.activeTab = '1'
        this.$refs.addbookForm.resetFields()
      })
    },
    upBookClick () {
      this.$refs.addbookForm.validate(async (valid) => {
        if (!valid) return this.$message.error('请完善书籍表单的内容')
        const req = { ...this.addForm, createTime: dayjs(this.addForm.createTime).unix(), bookId: this.addForm.id }
        const data = await updateBook(req)
        if (data.code != 200) return this.$message.error(data.msg)

        this.$message.success(data.msg)

        this.activeTab = '1'
        this.$refs.addbookForm.resetFields()
        this.$router.back()
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.content-row {
  margin-top: 50px;
}

.el-tab-pane {
  text-align: left;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
